import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { fetchRegistration } from './auth.actions';

interface IResponseUser {
  token?: string;
  data: {
    email: string;
    password: string;
    fullName: string;
    id: string;
  };
}

interface iUser {
  user: IResponseUser;
  loading: boolean;
  error: unknown;
  success: boolean;
}

const initialState: iUser = {
	user: {
		token: '',
		data: { email: string, password: string, fullName: string, id: string }
	},
	loading: false,
	error: null,
	success: false
};

export const userRegistrationSlice = createSlice({
	name: 'userRegistration',
	initialState,
	reducers: {},
	extraReducers: (builder) => {
		builder.addCase(fetchRegistration.pending, (state) => {
			state.loading = true;
			state.error = null;
		}),
		builder.addCase(
			fetchRegistration.fulfilled,
			(state, action: PayloadAction<IResponseUser>) => {
				console.log('данные после регистрации', action.payload);
				state.user = action.payload;
				state.success = true;
			}
		),
		builder.addCase(fetchRegistration.rejected, (state, action) => {
			console.log('ошибка из слайса регистрации', action.payload);
			state.error = action.error.message;
		});
	}
});

export default userRegistrationSlice.reducer;
